<template>
  <div>
    <van-popup v-model="showPrice" class="totop-popup bg-white" position="bottom">
      <van-row class="popup-head" type="flex" justify="space-between">
        <van-col span="4"></van-col>
        <van-col span="8" class="head-text">加价转发</van-col>
        <van-col span="4" class="c-gray text-right" @click="showPrice = false">
          <van-icon name="cross"/>
        </van-col>
      </van-row>
      <div class="bg-white pd-all popup-body">
        <div class="tips">
          <span>免责声明：</span>请合理设置转发价，官方不负责由此产生的价格纠纷；所转发的产品，将由您为游客提供咨询解答服务
        </div>

        <div class="package-price" v-if="packages">
          <van-row 
            class="cate-item mg-top pd-btm"
            type="flex" 
            justify="space-between"
            v-for="(cate, index) in packages"
            :key="index"
          >
            <van-col span="15">
              <p>{{cate.name}}</p>
              <p class="c-gray-l mg-top-xs">{{cate.price_tips}}</p>
            </van-col>
            <van-col span="8">
              <p class="text-right sale-price">￥<em>{{parseFloat(cate.trade_price)}}</em></p>
              <van-stepper 
                v-model="stepper[index].earn"
                :min="Number(min[index])"
                :max="Number(max[index])"
                input-width="38px"
                @blur="blurValue(index, cate.trade_price)"
              />
              <p class="share-price c-buy">￥<b>{{stepper[index].share_price}}</b></p>
            </van-col>
          </van-row>
        </div>
      </div>
      
      <van-goods-action class="popup-footer van-hairline--top">
        <van-goods-action-button class="reset-btn" text="重置" @click="reset"/>
        <van-goods-action-button class="copy-btn" text="复制链接" @click="encrypt(1)"/>
        <van-goods-action-button type="buy" text="生成二维码" @click="encrypt(2)"/>
      </van-goods-action>
    </van-popup>

    <detail-poster
      ref="detail_poster"
      :show="show_poster"
      :banner="banner"
      :title="title"
      :price="lowest_price"
      :del="del_price"
      :sales="total_sales"
      :qrcode_text="qrcode"
      @close="show_poster = false"
    />
  </div>
</template>
<script>
import { 
	Popup,
	Icon,
	Button,
	Row,
  Col,
  Stepper,
	GoodsAction,
  GoodsActionButton,
  Toast,
  Dialog,
 } from "vant";
import Poster from '@views/product/components/poster'
import {
  getShortUrl
} from '@api/modules/product'

export default {
  name: 'add-price',
  components: {
		[Popup.name]: Popup,
		[Icon.name]: Icon,
		[Button.name]: Button,
		[Row.name]: Row,
    [Col.name]: Col,
    [Stepper.name]: Stepper,
		[GoodsAction.name]: GoodsAction,
    [GoodsActionButton.name]: GoodsActionButton,
    [Poster.name]: Poster
	},
  props: {
    detail: Object,
  },
  data() {
    return {
      showPrice: false,
      packages: [],
      banner: [],
      stepper: [],
      min: [],
      max: [],
      values: [],
      
      short_link: '', // 短连接
      short_link_way: 1, // 短连接用途，1：复制，2:二维码
      
      title: '',
      price: {},
      del_price: 0,
      lowest_price: 0,
      total_sales: 0,
      qrcode: '',
      show_poster: false, // 是否展示海报二维码
    }
  },
  watch: {
    detail: {
      handler() {
        this.title = this.detail.name
        this.banner = this.detail.detail.picture.product_pic
        this.packages = this.detail.packages
        this.setSharePrice(this.packages)
      },
      deep: true
    },
    stepper: {
      handler (nw) {
        nw.forEach(item => {
          item.share_price = (parseFloat(item.earn) + parseFloat(item.trade_price)).toFixed(2)
          item.share_price = parseFloat(item.share_price)
        })
        
      },
      deep: true
    },
    short_link(nw){
      if(nw){
        if(this.short_link_way == 1 ){
          this.copy(nw)
        }else{
          this.setPoster()
        }
      }
    }
  },
  methods: {
    init() {
      this.showPrice = true
    },
    // 设置初始值
    setSharePrice(cates){
      this.min = []
      let step = []
      cates.forEach(item => {
        let earn = parseFloat(item.sale_price) - parseFloat(item.trade_price),
            values = parseFloat(item.sale_price)
        
        if(item.forward_price_type == 1){
          item.forward_price_min = item.forward_price_min > item.trade_price ? item.forward_price_min : item.trade_price
          item.forward_price_max = item.forward_price_max > item.trade_price ? item.forward_price_max : item.trade_price
          if (item.sale_price < item.forward_price_min) {
            earn = parseFloat(item.forward_price_min) - parseFloat(item.trade_price);
            values = parseFloat(item.forward_price_min);
          } else if (item.sale_price > item.forward_price_max) {
            earn = parseFloat(item.forward_price_max) - parseFloat(item.trade_price);
            values = parseFloat(item.forward_price_max);
          }
          this.min.push(earn.toFixed(2));
          this.max.push(parseFloat(item.forward_price_max) - parseFloat(item.trade_price))

          item.price_tips = `转发价不高于￥${parseFloat(item.forward_price_max)}，不低于￥${earn}`
        }else{
          this.max.push(Number.POSITIVE_INFINITY)
          this.min.push(0)
        }
        earn = earn > 0 ? earn : 0

        this.values.push(values)

        step.push({
          id: item.id,
          earn: parseFloat(earn.toFixed(2)),
          sale_price: parseFloat(item.sale_price),
          trade_price: item.trade_price
        })
        
        this.total_sales += parseInt(item.sales)
      })
      this.stepper = step
    },
    blurValue(index, trade_price) {
      let step = Number(this.stepper[index].earn || 0),
            min = this.min[index],
            max = this.max[index]
        min = min ? min : 0
        max = max ? max : 0
      step = step < min ? min : (step > max ? max : step)
      let value = parseFloat(trade_price) + parseFloat(step)
      this.stepper[index].earn = parseFloat(step)
      this.values[index] = parseFloat(value)
    },
    // 重置
    reset() {
      this.setSharePrice(this.packages)
    },
    // TODO: 加密解密的方法还不确定
    async encrypt(type) {
      if(!this.stepper.length){
        Toast('操作失败，没有可转发的产品套餐')
        return false
      }
      let str = [];
      this.stepper.forEach(item => {
        str.push(`${item.id}_${item.earn}`)
      })
      str = str.join('-')
      const id = this.detail.id
      getShortUrl({
        id,
        str,
      }).then(res => {
          this.short_link_way = type
          this.short_link = res.data.url
      })
    },
    /**
     * 注意：火狐，Safari浏览器里需要用户主动触发复制粘贴事件
     * https://github.com/Inndy/vue-clipboard2/issues/52#issuecomment-515371050
     */
    mobileCopy(text) {
      Dialog.alert({
        message: '加价链接：' + text,
        confirmButtonText: '复制'
      }).then(() => {
        this.copy(text)
      })
    },
    // 复制链接
    copy(text) {
      this.$copyText(text).then((e) => {
        Toast('转发链接已复制成功！')
      }, (err) => {
        // Toast(err || '复制失败, 请稍后重试!');
        this.mobileCopy(text)
      })
      this.delLink()
    },
    delLink() {
      this.short_link = ''
    },
    // 展示二维码
    setPoster() {
      this.qrcode = this.short_link
      this.lowest_price = Math.min.apply(Math, this.stepper.map(item => item.share_price))
      this.del_price = this.stepper.find(item => item.share_price === this.lowest_price).sale_price
      this.delLink()
      this.show_poster = true
    }
  }
}
</script>
<style lang="less" scoped>
@import "~@style_m/basic/utils/index";
@import "~@style_m/components/popup";
@copy-btn-bg: fade(@color-main, 10%);
.totop-popup {
  overflow-y: hidden;
}
.tips {
  border-radius: @radius-default;
  padding: 10px;
  background-color: #fef5db;
  font-size: @size-default;
  span {
    color: #ff6633;
  }
}
.package-price {
  margin-bottom: 40px;
}
.popup-body {
  padding-bottom: 80px!important;
  height: calc(100vh - 80px);
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}
.cate-item {
  border-bottom: @border-default;
}
.van-stepper {
  text-align: right;
  position: relative;
  &:after {
    content: '+';
    position: absolute;
    left: 0;
    top: 44%;
    transform: translateY(-50%);
    font-size: 20px;
    font-weight: 500;
    color: @gray-6;
  }
}
.sale-price {
  font-size: 14px;
}
.share-price {
  position: relative;
  padding-top: 10px;
  margin-top: 10px;
  border-top: 1px solid @gray-6;
  text-align: right;
  line-height: 1;
  &::before {
    content: '转发价';
    position: absolute;
    left: 0;
    bottom: 2px;
    font-size: @font-size-default;
    color: @gray-6;
  }
  b {
    font-size: 18px;
  }
}

.reset-btn {
  flex: 0 0 22.7%;
  border-right: @border-default;
}
.copy-btn {
  background-color: @copy-btn-bg;
  border-right: @border-default;
}

</style>